package com.wiretap.service.impl;

import java.util.Date;
import java.util.List;

import com.wiretap.dao.MessageDao;
import com.wiretap.dao.MotionDao;
import com.wiretap.dao.UserDao;
import com.wiretap.po.Message;
import com.wiretap.po.Motion;
import com.wiretap.po.User;
import com.wiretap.service.MotionService;
import com.wiretap.util.CommenUtil;
import com.wiretap.util.Pager;

public class MotionServiceImpl implements MotionService {

	private MotionDao motionDao;
	private MessageDao messageDao;
	private UserDao userDao;

	@Override
	public void addMotion(String eId, String eContent, String msgId,
			String phone) throws Exception {
		Motion motion = new Motion();
		motion.setAddDate(new Date());
		motion.seteContent(eContent);
		motion.setEid(eId);
		motion.setPhone(phone);
		motion.setMsgId(msgId);
		motionDao.addMotion(motion);
	}

	@Override
	public void updateMotionExcuteStatus(String id, boolean excuted)
			throws Exception {
		try {
			String[] ids = id.split(",");

			for (int i = 0; i < ids.length; i++) {
				String _id = ids[i];
				if (CommenUtil.isEmpty(_id))
					continue;
				Motion motion = motionDao.getMotionById(_id);
				if (motion != null) {
					motion.setExecuted(excuted);
					messageDao.updateMessageDeleteStatus(motion.getMsgId(),
							true);
					motionDao.updateMotion(motion);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public Pager<Motion> getAllMotionByPhone(String phone, int currentPage,
			int pageSize) throws Exception {
		return motionDao.getAllMotionByPhone(phone, currentPage, pageSize);
	}

	@Override
	public List<Motion> getUnExcuteMotionByPhone(String phone) throws Exception {
		return motionDao.getUnExcuteMotionByPhone(phone);
	}

	@Override
	public boolean removeMotion(String id) throws Exception {
		if (CommenUtil.isEmpty(id))
			return false;
		return motionDao.removeMotion(id) > 0;
	}

	@Override
	public boolean addMotionByMessage(String mid) throws Exception {
		if (CommenUtil.isEmpty(mid))
			return false;
		Message message = messageDao.getMessageById(mid);
		if (message == null)
			return false;
		try {
			User user = userDao.getUserByPhone(message.getPhone());
			if (!user.isRemoteDelStatus()) {
				user.setRemoteDelStatus(true);
				userDao.updateUser(user);
			}
			if (!message.isDeleted()) {
				addMotion(message.getCid(), message.getContent(), mid,
						message.getPhone());
			}
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	public void setMotionDao(MotionDao motionDao) {
		this.motionDao = motionDao;
	}

	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

}
